<template>
  <el-tabs
    type="border-card"
    style="margin: 0 20px; height: 93vh"
    v-model="activeName"
  >
    <el-tab-pane label="历史数据" name="历史数据">
      <el-form inline :model="form">
        <el-form-item label="采集通道">
          <el-select v-model="form.tunnel" size="mini">
            <el-option label="全部" value="00"></el-option>
            <el-option
              :label="item.tunnelName"
              :value="item.tunnelNum"
              v-for="(item, index) in form.listSensorTunnel"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
            type="datetime"
            placeholder="选择开始时间"
            size="mini"
            v-model="form.startTime"
            default-time="00:00:00"
            :picker-options="startTimePicker"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            type="datetime"
            placeholder="选择结束时间"
            size="mini"
            v-model="form.endTime"
            default-time="00:00:00"
            :picker-options="endTimePicker"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="info" size="mini" @click="search(1)">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            type="warning"
            size="mini"
            @click="exportExcel('#tab', '岩土历史数据')"
            >导出</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        :data="tableData"
        id="tab"
        v-if="tableData"
        :row-class-name="tableRowClassName"
        v-loading="loading"
      >
        <el-table-column
          prop="label"
          label="监测站点"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="tunnel"
          label="通道号"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="type"
          label="监测类型"
          align="center"
        ></el-table-column>
        <el-table-column
          :prop="item.prop"
          :label="item.label"
          align="center"
          v-for="(item, index) in tableHead"
          :key="index"
        ></el-table-column>
        <el-table-column
          prop="theDate"
          label="采集时间"
          align="center"
        ></el-table-column>
      </el-table>
      <el-row type="flex" justify="end">
        <el-col :span="10">
          <el-pagination
            background
            :current-page="pageData.currentPage"
            layout="total, prev, pager, next, jumper"
            :total="pageData.count"
            :page-size="pageData.pageSize"
            @current-change="handleCurrentChange"
            v-if="pageData.count && pageData.count != 0"
          >
          </el-pagination>
        </el-col>
      </el-row>
    </el-tab-pane>
  </el-tabs>
</template>

<script>
import Axios from "axios";
import moment from "moment";
import FileSaver from "file-saver";
import XLSX from "xlsx";
import * as serviceApi from "../../../common/service.config";
Axios.defaults.withcredentials = true;

export default {
  name: "Yantu",
  props: {
    node: Object,
  },
  data() {
    return {
      activeName: "历史数据",
      form: {
        listSensorTunnel: null,
        startTime: null,
        endTime: moment().format("YYYY-MM-DD 00:00:00"),
        startTimeMin: null,
        tunnel: "00",
      },
      tableHead: null,
      tableData: null,
      pageData: {
        currentPage: null,
        count: null,
        pageSize: null,
      },
      loading: null,
    };
  },
  computed: {
    startTimePicker() {
      return {
        disabledDate: (time) =>
          this.form.startTime
            ? time.getTime() < new Date(this.form.startTimeMin).getTime() ||
              time.getTime() > new Date(this.form.endTime).getTime()
            : false,
      };
    },
    endTimePicker() {
      return {
        disabledDate: (time) =>
          this.form.endTime
            ? time.getTime() > new Date().getTime() ||
              time.getTime() < new Date(this.form.startTime).getTime()
            : false,
      };
    },
  },
  methods: {
    exportExcel(dom, title) {
      /* out-table关联导出的dom节点  */
      var wb = XLSX.utils.table_to_book(document.querySelector(dom));
      /* get binary string as output */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          `${this.node.label}${title}.xlsx`
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    intToChinese(str) {
      str = str + "";
      var len = str.length - 1;
      var idxs = [
        "",
        "十",
        "百",
        "千",
        "万",
        "十",
        "百",
        "千",
        "亿",
        "十",
        "百",
        "千",
        "万",
        "十",
        "百",
        "千",
        "亿",
      ];
      var num = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
      return str.replace(/([1-9]|0+)/g, function ($, $1, idx, full) {
        var pos = 0;
        if ($1[0] != "0") {
          pos = len - idx;
          if (idx == 0 && $1[0] == 1 && idxs[len - idx] == "十") {
            return idxs[len - idx];
          }
          return num[$1[0]] + idxs[len - idx];
        } else {
          var left = len - idx;
          var right = len - idx + $1.length;
          if (Math.floor(right / 4) - Math.floor(left / 4) > 0) {
            pos = left - (left % 4);
          }
          if (pos) {
            return idxs[pos] + num[$1[0]];
          } else if (idx + $1.length >= len) {
            return "";
          } else {
            return num[$1[0]];
          }
        }
      });
    },
    querySensorTunnel(resultObj) {
      if (resultObj != null && resultObj != "") {
        let tunnelList = resultObj.parameter.list;
        if (
          tunnelList != "" &&
          tunnelList != null &&
          typeof tunnelList != "undefined"
        ) {
          if (tunnelList.length != "0") {
            let list = [];
            for (let i = 0; i < tunnelList.length; i++) {
              if (tunnelList[i].status == "00") {
                let tunnelNum = tunnelList[i].sensorNumber;
                tunnelNum = tunnelNum.substring(tunnelNum.length - 2);
                list.push({
                  tunnelNum: tunnelList[i].sensorNumber,
                  tunnelName: "通道" + this.intToChinese(tunnelNum),
                });
              }
            }
            this.form.listSensorTunnel = list;
          }
        }
      }
    },
    queryRockHisData(resultObj) {
      if (
        resultObj.parameter.list != null &&
        resultObj.parameter.list != "undefined"
      ) {
        if (resultObj.parameter.list.length != 0) {
          let d = resultObj.parameter;
          if (d.list[0].dataType === "01") {
            this.tableHead = [
              { prop: "data", label: "传感器原始测值（mm）" },
              { prop: "nozzle_height", label: "传感器埋深(m)" },
              { prop: "displaceValue", label: "位移(mm)" },
              { prop: "changeValue", label: "变化(mm/h)" },
            ];
            for (let i = 0; i < d.list.length; i++) {
              d.list[i].label = this.node.label;
              d.list[i].type = "测斜";
              d.list[i].data = d.list[i].data.toFixed(1);
              d.list[i].theDate = moment(d.list[i].theDate).format(
                "YYYY-MM-DD HH:mm:ss"
              );
            }
            this.tableData = d.list;
            return;
          }
          if (d.list[0].dataType === "02") {
            this.tableHead = [{ prop: "data", label: "数值(mm)" }];
            for (let i = 0; i < d.list.length; i++) {
              d.list[i].label = this.node.label;
              d.list[i].type = "裂缝";
              d.list[i].data = d.list[i].data.toFixed(1);
              d.list[i].theDate = moment(d.list[i].theDate).format(
                "YYYY-MM-DD HH:mm:ss"
              );
            }
            this.tableData = d.list;
            return;
          }
          if (d.list[0].dataType === "04") {
            this.tableHead = [{ prop: "data", label: "数值(kpa)" }];
            for (let i = 0; i < d.list.length; i++) {
              d.list[i].label = this.node.label;
              d.list[i].type = "土壤湿度";
              d.list[i].data = d.list[i].data.toFixed(1);
              d.list[i].theDate = moment(d.list[i].theDate).format(
                "YYYY-MM-DD HH:mm:ss"
              );
            }
            this.tableData = d.list;
            return;
          }
          if (d.list[0].dataType === "05") {
            this.tableHead = [{ prop: "data", label: "数值(kpa)" }];
            for (let i = 0; i < d.list.length; i++) {
              d.list[i].label = this.node.label;
              d.list[i].type = "流量";
              d.list[i].data = d.list[i].data.toFixed(3);
              d.list[i].theDate = moment(d.list[i].theDate).format(
                "YYYY-MM-DD HH:mm:ss"
              );
            }
            this.tableData = d.list;
            return;
          }
          if (d.list[0].dataType === "0301") {
            this.tableHead = [{ prop: "data", label: "数值（kPa）" }];
            for (let i = 0; i < d.list.length; i++) {
              d.list[i].label = this.node.label;
              d.list[i].type = "渗压";
              d.list[i].data = d.list[i].data.toFixed(1);
              d.list[i].theDate = moment(d.list[i].theDate).format(
                "YYYY-MM-DD HH:mm:ss"
              );
            }
            this.tableData = d.list;
            return;
          }
          if (d.list[0].dataType === "0302") {
            this.tableHead = [{ prop: "data", label: "数值（kPa）" }];
            for (let i = 0; i < d.list.length; i++) {
              d.list[i].label = this.node.label;
              d.list[i].type = "渗压";
              d.list[i].data = d.list[i].data.toFixed(1);
              d.list[i].theDate = moment(d.list[i].theDate).format(
                "YYYY-MM-DD HH:mm:ss"
              );
            }
            this.tableData = d.list;
            return;
          }
          if (d.list[0].dataType === "03") {
            this.tableHead = [{ prop: "data", label: "数值（kPa）" }];
            for (let i = 0; i < d.list.length; i++) {
              d.list[i].label = this.node.label;
              d.list[i].type = "渗压";
              d.list[i].data = d.list[i].data.toFixed(1);
              d.list[i].theDate = moment(d.list[i].theDate).format(
                "YYYY-MM-DD HH:mm:ss"
              );
            }
            this.tableData = d.list;
            return;
          }
          if (d.list[0].dataType === "06") {
            this.tableHead = [{ prop: "data", label: "数值(mm)" }];
            for (let i = 0; i < d.list.length; i++) {
              d.list[i].label = this.node.label;
              d.list[i].type = "沉降";
              d.list[i].data = d.list[i].data.toFixed(1);
              d.list[i].theDate = moment(d.list[i].theDate).format(
                "YYYY-MM-DD HH:mm:ss"
              );
            }
            this.tableData = d.list;
            return;
          }
          if (d.list[0].dataType === "07") {
            this.tableHead = [{ prop: "data", label: "数值（kPa）" }];
            for (let i = 0; i < d.list.length; i++) {
              d.list[i].label = this.node.label;
              d.list[i].type = "土压力";
              d.list[i].data = d.list[i].data.toFixed(1);
              d.list[i].theDate = moment(d.list[i].theDate).format(
                "YYYY-MM-DD HH:mm:ss"
              );
            }
            this.tableData = d.list;
            return;
          }
          if (d.list[0].dataType === "08") {
            this.tableHead = [{ prop: "data", label: "测值（με）" }];
            for (let i = 0; i < d.list.length; i++) {
              d.list[i].label = this.node.label;
              d.list[i].type = "应变";
              d.list[i].data = d.list[i].data.toFixed(1);
              d.list[i].theDate = moment(d.list[i].theDate).format(
                "YYYY-MM-DD HH:mm:ss"
              );
            }
            this.tableData = d.list;
            return;
          }
          this.tableHead = [{ prop: "data", label: "数值(mm)" }];
          for (let i = 0; i < d.list.length; i++) {
            d.list[i].label = this.node.label;
            d.list[i].type = "未知";
            d.list[i].data = d.list[i].data.toFixed(1);
            d.list[i].theDate = moment(d.list[i].theDate).format(
              "YYYY-MM-DD HH:mm:ss"
            );
          }
          this.tableData = d.list;
        }
      }
    },
    search(currentPage) {
      this.loading = true;
      let queryData = {
        startTime: moment(this.form.startTime).format("YYYY-MM-DD"),
        endTime: moment(this.form.endTime).format("YYYY-MM-DD"),
        tunnel: this.form.tunnel,
      };
      Axios({
        url: serviceApi.KB_API,
        method: "post",
        data: `appMsg={"parameter":"{\\"sensorNumber\\":\\"${this.node.sensorNumber}\\",\\"tunnel\\":\\"${queryData.tunnel}\\",\\"startTime\\":\\"${queryData.startTime}\\",\\"endTime\\":\\"${queryData.endTime}\\",\\"page\\":{\\"currentPage\\":${currentPage},\\"pageSize\\":10}}","serviceCode":"groundHistory","timestamp":"","uuid":""}`,
      }).then((res) => {
        this.loading = false;
        this.pageData = res.data.parameter.page;
        this.queryRockHisData(res.data);
      });
    },
    handleCurrentChange(val) {
      this.search(val);
    },
    tableRowClassName({ row }) {
      if (row.dataType == "04") {
        if (row.tunnel == "01") {
          return "row01";
        } else if (row.tunnel == "02") {
          return "row02";
        } else {
          return "row03";
        }
      }
    },
  },
  created() {
    this.loading = true;
    Axios({
      url: serviceApi.KB_API,
      method: "post",
      data: `appMsg={"parameter":"{\\"sensorId\\":\\"${this.node.id}\\",\\"dataType\\":\\"\\"}","serviceCode":"listSensorTunnel","timestamp":"","uuid":""}`,
    }).then((res) => {
      this.querySensorTunnel(res.data);
      let startTime = moment().subtract(1860, "d").format("YYYY-MM-DD");
      this.form.startTime = moment(startTime).format("YYYY-MM-DD 00:00:00");
      this.form.startTimeMin = this.form.startTime;
      let queryData = {
        startTime: startTime,
        endTime: moment().format("YYYY-MM-DD"),
      };
      Axios({
        url: serviceApi.KB_API,
        method: "post",
        data: `appMsg={"parameter":"{\\"sensorNumber\\":\\"${this.node.sensorNumber}\\",\\"tunnel\\":\\"00\\",\\"startTime\\":\\"${queryData.startTime}\\",\\"endTime\\":\\"${queryData.endTime}\\",\\"page\\":{\\"currentPage\\":1,\\"pageSize\\":10}}","serviceCode":"groundHistory","timestamp":"","uuid":""}`,
      }).then((res) => {
        this.loading = false;
        this.pageData = res.data.parameter.page;
        this.queryRockHisData(res.data);
      });
    });
  },
};
</script>

<style lang="less" scoped>
.el-table {
  /deep/ .row01 {
    background: #ffbab7;
  }
  /deep/ .row02 {
    background: #97cbff;
  }
  /deep/ .row03 {
    background: #ffffa3;
  }
}
</style>